package utils

import (
	"errors"
	"github.com/golang-jwt/jwt/v5"
)

// GenerateJWT 生成jwt
func GenerateJWT[T any](data T, secret string) (string, error) {
	secretKey := []byte(secret)
	toMap := StructToMap(data)
	claims, err := MapToStruct[jwt.MapClaims](toMap)
	if err != nil {
		return "", err
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(secretKey)
}

// ParseJWT 解析jwt
func ParseJWT[T any](tokenStr string, secret string) (*T, error) {
	secretKey := []byte(secret)
	token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.New("Unexpected signing method")
		}
		return secretKey, nil
	})
	if err != nil {
		return nil, err
	}
	claims, ok := token.Claims.(jwt.MapClaims)
	if ok && token.Valid {
		return MapToStruct[T](claims)
	}
	return nil, errors.New("Invalid token")
}
